#!/usr/local/bin/php
<?php

$table = false;
$app = realpath( 'www' );

$what = $argv[1];
$name = $argv[2];

if( $argc <= 1 ) {
	die( "Usage ./scripts/generate [controller|model] name\n" );
}

if( file_exists( $app.'/foundry.config.php' ) ) {
	include_once( $app.'/foundry.config.php' );
}


$filter = array(
	'/\%NS\%/'		=> Foundry::config( 'namespace' ),
	'/\%NAME\%/'	=> $name,
);

Foundry::load( 'ACTIVERECORD_inflector', false, false );

$model = Inflector::pluralize( $name );

$key = false;

switch( $what ) {
	case 'obfuscatedController':
	
		$key = md5( uniqid( rand(), true ) );
	
	case 'controller':

		$controller = file_get_contents(
			'./scripts/skeleton/controller.skel.php' );
		
		echo "Converting controller skeleton file...\n";
		
		$controller = preg_replace(
			array_keys( $filter ),
			$filter,
			$controller );
		
		echo 'Creating app/controllers/'.$name.".class.php...\n";
		file_put_contents( './app/controllers/'.$name.'.class.php',
			$controller );
			
		echo 'mkdir app/views/'.$name."/\n";
		if( !is_dir( './app/views/'.$name.'/' ) ) {
			mkdir( './app/views/'.$name.'/' );
		}
		
		echo "Creating default view...\n";
		
		copy('./scripts/skeleton/view.skel.php',
			'./app/views/'.$name.'/main.tpl' );
		
		echo "Updating modules config...\n";
		$modules = parse_ini_file( './config/modules.conf', true );

		if( !$modules['default'] ) {
			$modules['default'] = array( 'controller' => $name );
		}
		
		$modules[$name] = array( 'default'	=> 'main', 'main' => 'false' );
		
		if( $key !== false && strlen( $key ) == 32 ) {
			$modules[$name]['__obKey'] = $key;
		}
		
		writeConfFile( 'modules', $modules );
		
		$routes = parse_ini_file( './config/routes.conf' );
		
		$routes[$name] = 'node';
		
		echo "Updating routes config...\n";
		writeConfFile( 'routes', $routes, false );
		
		echo "Controller created\n".
			"Make sure to modify the config/routes.conf to suit your ".
			"purposes\n";
			
		break;
		
	case 'model':
	
		echo "Checking for table ".foundry::config( 'namespace' ).
		$model."...\n";
		
		$sql = 'describe '.foundry::config('namespace').$model;
		$dbh = FoundryRegistry::get( 'dbh' );
		
		try {

			$stmt = $dbh->prepare( $sql );
			$stmt->execute();

			$row = $stmt->fetch();

		} catch( PDOException $e ) {
			echo 'Error: '.$e->getMessage()."\n";
			exit;
		}
		
		if( !is_array( $row ) || count( $row ) < 1 ) {
			echo "Table ".foundry::config( 'namespace' ).$model." could not ".
				"be found!\nPlease create table and re-run generate\n";
			exit;
		}

		$model = file_get_contents( './scripts/skeleton/model.skel.php' );
		echo "Converting model skeleton file...\n";
		
		$model = preg_replace(
			array_keys( $filter ),
			$filter,
			$model );
			
		echo "Creating ./app/models/".$name.".class.php...\n";
		file_put_contents( './app/models/'.$name.'.class.php', $model );

		echo "Model created!\nRunning analyzer...";
		
		$command = "./scripts/analyze";
		
		exec( $command );
		
		echo "Finished.\n";

		break;
		
	case 'node':
		
		if( strpos( $name, ':' ) === false ) {
			echo "Could not find node namespace, format is\n".
				"controller:node (ex: calendar:viewEvent)\n";
			exit(1);
		}
		
		$temp = explode( ':', $name );
		$module = $temp[0];
		$node = $temp[1];

		if( strlen( $module ) < 1 || strlen( $node ) < 1 ) {
			echo "Could not find node namespace, format is\n".
				"controller:node[ callback] (ex: calendar:viewEvent)\n";
			exit(1);
		
		}

		$modules = parse_ini_file( './config/modules.conf', true );

		echo "Checking for module ".$module."... ";

		if( !array_key_exists( $module, $modules ) ) {
			echo "\nCould not find module ".$module."\n".
				"Please run\n./scripts/generate module ".$module."\n";
			exit(1);
		}
		
		echo "Found\n";
		
		$nodes = $modules[$module];
		
		echo "Checking for node ".$module.':'.$node."... ";
		
		if( array_key_exists( $node, $nodes ) ) {
			echo "\nNode ".$module.':'.$node." already exists!\n";
			exit(1);
		}

		echo "Ok\nAdding ".$node." to node list... ";
		
		$callback = 'false';
		
		if( $argv[3] ) {
			$callback = $argv[3];
		}
		
		$modules[$module][$node] = $callback;

		echo "Ok\nUpdating modules file... ";

		writeConfFile( 'modules', $modules );

		echo "Ok\nDone!\n";

		break;


}

function writeConfFile( $name, $array, $multi = true )
{

	$out = '';
	foreach( $array as $key => $val ) {
	
		if( $multi === true ) {
			$out .= "[".$key."]\n";
			
			foreach( $val as $k => $v ) {
				$out .= $k.' = "'.$v.'"'."\n";
			}
		} else {
			$out .= $key.' = "'.$val.'"'."\n";
		}
		
		$out .= "\n\n";
	}
	
	file_put_contents( './config/'.$name.'.conf', $out );

}

	
?>
